from rest_framework import serializers
from .models import Song, Playlist, PlayHistory

class SongSerializer(serializers.ModelSerializer):
    audio = serializers.SerializerMethodField()
    cover = serializers.SerializerMethodField()

    class Meta:
        model = Song
        fields = '__all__'

    def get_audio(self, obj):
        request = self.context.get('request')
        if obj.audio:
            return request.build_absolute_uri(obj.audio.url)
        return None

    def get_cover(self, obj):
        request = self.context.get('request')
        if obj.cover:
            return request.build_absolute_uri(obj.cover.url)
        return None


class PlaylistSerializer(serializers.ModelSerializer):
    songs = SongSerializer(many=True, read_only=True)

    class Meta:
        model = Playlist
        fields = '__all__'

class PlayHistorySerializer(serializers.ModelSerializer):
    song = SongSerializer(read_only=True)

    class Meta:
        model = PlayHistory
        fields = '__all__'
